package api

import (
	"github.com/gin-gonic/gin"
	"middleware/validation"
	"net/http"
	"pkg/app"
	"pkg/e"
	"service/auth_service"
	"util"
)

type auth struct {
	Username string `valid:"Required;MaxSize(50)"`
	Password string `valid:"Required;MaxSize(50)"`
}

// 登录
func GetAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	valid := validation.Validation{}

	username := c.Query("username")
	password := c.Query("password")

	a := auth{Username: username, Password: password}
	ok, _ := valid.Valid(&a)

	if !ok {
		app.MarkErrors(valid.Errors)
		appG.Response400(nil)
		return
	}

	authService := auth_service.Auth{Username: username, Password: password}
	isExist, id, err := authService.Check()
	if err != nil {
		appG.Response500(e.ERROR_CHECK_TOKEN_FAIL, nil)
		return
	}

	if !isExist {
		appG.Response(http.StatusUnauthorized, e.ERROR_LOGIN_TOKEN_FAIL, nil)
		return
	}

	// 获取 token
	token, err := util.GenerateToken(id, username)
	if err != nil {
		appG.Response500(e.ERROR_ADD_TOKEN, nil)
	}

	// 返回token
	data := map[string]string{
		"token": token,
	}
	appG.Response200(data)
}
